package com.hxd.otc.module.fiat_deal.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.BaseRecyclerFragment;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.module.fiat_deal.adapter.DealAdapter;
import com.hxd.otc.module.fiat_deal.bean.DealRequestBean;
import com.hxd.otc.module.fiat_deal.bean.DealResultDataBean;
import com.hxd.otc.module.fiat_deal.bean.DealTeamBean;
import com.hxd.otc.module.fiat_deal.contract.DealListContract;
import com.hxd.otc.module.fiat_deal.presenter.DealListPresenter;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.module.my.activity.AccountInfoActivity;
import com.hxd.otc.module.my.activity.BankCardActivity;
import com.hxd.otc.module.my.activity.SecurityCenterActivity;
import com.hxd.otc.module.order.activity.BuyOrderDetailActivity;
import com.hxd.otc.module.order.activity.OrderFinishedActivity;
import com.hxd.otc.module.order.activity.SaleOrderDetailActivity;
import com.hxd.otc.module.order.bean.AllOrderBean;
import com.hxd.otc.module.order.fragment.AllOrderFragment;
import com.hxd.otc.utils.UIUtils;

/**
 * Created by lzy on 2018/9/17 0017.
 * description ${交易列表Fragment}
 */
public class DealListFragment extends BaseRecyclerFragment<DealListPresenter, DealAdapter, DealResultDataBean.Data> implements DealListContract.View, DealAdapter.OnTransactionListener {


    public static final String EXTRA_DEAL_TYPE = "dealType";//交易类型，买入、骂出
    public static final String EXTRA_COIN_TYPE = "coinType";//币种类型
    public static final String EXTRA_COIN_INFO = "coinInfo";//币种信息
    private DealDialogFragment mDealDialogFragment;

    @Override
    protected void initView() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mPresenter.setDealTeamBean((DealTeamBean) arguments.getSerializable(EXTRA_COIN_INFO));
            mPresenter.setDealType(arguments.getInt(EXTRA_DEAL_TYPE, Constant.Deal.TYPE_BUY));
            mPresenter.setCoinType(arguments.getString(EXTRA_COIN_TYPE));
            mPresenter.setFiat(mPresenter.getDealTeamBean().getSupportCurrencyCodeArr().get(0));
        }
        super.initView();
    }

    @Override
    protected DealListPresenter createPresenter() {
        return new DealListPresenter(this);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.layout_recycler;
    }

    @Override
    protected DealAdapter createAdapter() {
        DealAdapter dealAdapter = new DealAdapter(getContext());
        dealAdapter.setDealType(mPresenter.getDealType());
        dealAdapter.setOnItemClickListener(this);
        dealAdapter.setOnTransactionListener(this);
        return dealAdapter;
    }

    public void updateFilterConditions() {
        if (isAdded() && getUserVisibleHint()) {
            assert getParentFragment() != null;
            mPresenter.setFiat(((SubDealFragment) getParentFragment()).getFiat());
            mPresenter.setBankTypeValue(((SubDealFragment) getParentFragment()).getBankTypeValue());
            mRefreshLayout.autoRefresh(0, 10, 1);
        }
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        assert getParentFragment() != null;
        String newFiat = ((SubDealFragment) getParentFragment()).getFiat();
        String oldFiat = mPresenter.getFiat();

        String newBankTypeValue = ((SubDealFragment) getParentFragment()).getBankTypeValue();
        String oldBankTypeValue = mPresenter.getBankTypeValue();

        if (getUserVisibleHint() && !(newFiat.equals(oldFiat) && newBankTypeValue.equals(oldBankTypeValue))) {
            mPresenter.setFiat(newFiat);
            mPresenter.setBankTypeValue(newBankTypeValue);
            mRefreshLayout.autoRefresh(0, 10, 1);
        }
        //当页面可见时进行定时任务
        if (getUserVisibleHint()) {
            startAutoRefresh();
        } else {
            stopAutoRefresh();
        }
    }

    /**
     * 开启定时刷新任务
     */
    private void startAutoRefresh() {
//        if (mDisposable != null && !mDisposable.isDisposed()) {
//            return;
//        }
//        mDisposable = Flowable.interval(Constant.Deal.DEAL_LIST_AUTO_REFRESH_TIME, TimeUnit.SECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
//                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
//                    @SuppressLint("DefaultLocale")
//                    @Override
//                    public void accept(Long aLong) throws Exception {
//                        mRefreshLayout.autoRefresh(0, 10, 1);
//                    }
//                })
//                .subscribe();
    }

    @Override
    public void onStop() {
        super.onStop();
        stopAutoRefresh();
    }

    /**
     * 停止定时刷新任务
     */
    private void stopAutoRefresh() {
//        if (mDisposable != null && !mDisposable.isDisposed()) {
//            mDisposable.dispose();
//        }
//        mDisposable = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            startAutoRefresh();
        }
    }

    @Override
    public void onTransaction(int position, DealResultDataBean.Data item, final int dealType) {
        //是否登录
        if (!UserHelper.isLogin()) {
            $startActivity(LoginActivity.class);
            return;
        }

        if (UserHelper.getId().equals(item.userId)) {
            showToast(getString(R.string.not_operation_self_advert, getString(dealType == Constant.Deal.TYPE_BUY ? R.string.publish_advertisement_buy : R.string.sell)));
            return;
        }

        String transactionPair = mPresenter.getTransactionPair();

        //是否有设置交易密码
        if (dealType == Constant.Deal.TYPE_SELL && (!UserHelper.isSetExValidType())) {
            final MultipleBlocksDialog dailog = new MultipleBlocksDialog(getActivity());
            dailog.setContent(getActivity().getString(R.string.wallet_tpw_way_dialog_content));
            dailog.setTitle(getActivity().getString(R.string.wallet_tpw_way_dialog_title));
            dailog.setTvCancle(getActivity().getString(R.string.cancel));
            dailog.setTvSure(getActivity().getString(R.string.wallet_common_ok), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dailog.dismiss();
                    Intent intent = new Intent(getActivity(), SecurityCenterActivity.class);
                    getActivity().startActivity(intent);
                }
            });
            dailog.show();
            return;
        }

//        if (TextUtils.isEmpty(UserHelper.getMobile())) {
//            final MultipleBlocksDialog dailog = new MultipleBlocksDialog(getActivity());
//            dailog.setContent(getActivity().getString(R.string.without_phone_verified));
//            dailog.setTitle(getActivity().getString(R.string.bind_phone));
//            dailog.setTvCancle(getActivity().getString(R.string.cancel));
//            dailog.setTvSure(getActivity().getString(R.string.wallet_common_ok), new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    dailog.dismiss();
//                    Intent intent = new Intent(getActivity(), SecurityCenterActivity.class);
//                    getActivity().startActivity(intent);
//                }
//            });
//            dailog.show();
//            return;
//        }

        if (TextUtils.isEmpty(UserHelper.getNickName())) {
            final MultipleBlocksDialog dailog = new MultipleBlocksDialog(getActivity());
            dailog.setContent(getActivity().getString(R.string.without_nickname_verified));
            dailog.setTitle(getActivity().getString(R.string.bind_nickname));
            dailog.setTvCancle(getActivity().getString(R.string.cancel));
            dailog.setTvSure(getActivity().getString(R.string.wallet_common_ok), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dailog.dismiss();
                    Intent intent = new Intent(getActivity(), AccountInfoActivity.class);
                    getActivity().startActivity(intent);
                }
            });
            dailog.show();
            return;
        }

        if (UserHelper.isNonInductivePaySilver()){//无感商 不能进行买入卖出操作
            showToast(getString(R.string.nosense_no_buy_and_sell_operation));
            return;
        }
        showDealDialog(item, dealType, transactionPair);
    }

    private void showDealDialog(DealResultDataBean.Data item, final int dealType, String transactionPair) {
        UIUtils.dismissDialogFragment(mDealDialogFragment);
        mDealDialogFragment = DealDialogFragment.getInstance(item, dealType, transactionPair);
        mDealDialogFragment.setOnConfirmListener(new DealDialogFragment.OnConfirmListener() {
            @Override
            public void onConfirm(DealRequestBean bean) {
                setDealDialogConfirmBtnEnable(false);
                if (dealType == Constant.Deal.TYPE_BUY) {
                    mPresenter.dealBuy(bean);
                } else {
                    mPresenter.dealSale(bean);
                }
            }
        }).showAllowingStateLoss(getChildFragmentManager(), "deal");
    }


    @Override
    public void buySuccess(AllOrderBean.DataBean dataBean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(AllOrderFragment.ORDERINFO, dataBean);
        bundle.putBoolean(OrderFinishedActivity.ISREFRESH_ORDER_LIST_DATA, true);
        bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, true);
        $startActivity(BuyOrderDetailActivity.class, bundle, false);
        setDealDialogConfirmBtnEnable(true);
        UIUtils.dismissDialogFragment(mDealDialogFragment);
    }

    @Override
    public void saleSuccess(AllOrderBean.DataBean dataBean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(AllOrderFragment.ORDERINFO, dataBean);
        bundle.putBoolean(OrderFinishedActivity.ISREFRESH_ORDER_LIST_DATA, true);
        bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, true);
        $startActivity(SaleOrderDetailActivity.class, bundle, false);
        setDealDialogConfirmBtnEnable(true);
        UIUtils.dismissDialogFragment(mDealDialogFragment);
    }

    @Override
    public void onResultError(int code, String errMessage) {
        MultipleBlocksDialog multipleDialog = new MultipleBlocksDialog(getContext());
        multipleDialog.setTitle(getString(R.string.hint)).setContent(errMessage);
        multipleDialog.show();
        multipleDialog.setOnDialogItemClickListener(new MultipleBlocksDialog.OnDialogItemClickListener() {
            @Override
            public void onSure() {
                $startActivity(BankCardActivity.class);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    @Override
    public void onDealFail() {
        //用于恢复对话框确认按钮点击状态
        setDealDialogConfirmBtnEnable(true);
    }

    private void setDealDialogConfirmBtnEnable(boolean enable) {
        if (mDealDialogFragment != null) {
            mDealDialogFragment.setDealDialogConfirmBtnEnable(enable);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopAutoRefresh();
    }
}
